<?php
declare(strict_types=1);
namespace cms\exam\admin\api_controller;

use cms\exam\request\RoomFormRequest;
use cms\exam\service\RoomService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Psr\Http\Message\ResponseInterface;

/**
 * Class RoomController
 * @package cms\exam\admin\api_controller
 * @Controller(prefix="api/exam/admin_room")
 */
class RoomController extends CommonController
{
    /**
     * @Inject()
     * @var RoomService 
     */
    protected RoomService $roomService;
    /**
     * @param RoomFormRequest $request
     * @return ResponseInterface
     * @PostMapping(path="create")
     */
    public function create(RoomFormRequest $request): ResponseInterface
    {
        $app = $this->_getApp(true);
        // $request->validate('create');
        $form_data = $request->validated();
        $form_data['app_id'] = $app->id;
        $result = $this->roomService->model->create($form_data);
        return $this->success('请求成功', $result);
    }

    /**
     * @param RoomFormRequest $request
     * @return ResponseInterface
     * @PostMapping(path="update")
     */
    public function update(RoomFormRequest $request): ResponseInterface
    {
        // $request->validate('update');
        $form_data = $request->validated();
        $id = (int) $this->request->input('id', 0);
        $data = $this->roomService->getDataById($id, true);
        $data->fill($form_data);
        $data->save();
        return $this->success('请求成功', $data);
    }


    /**
     * @return ResponseInterface
     * @RequestMapping(path="retrieve")
     */
    public function retrieve(): ResponseInterface
    {
        $app = $this->_getApp(true);
        $query = $this->roomService->model->where('app_id', $app->id);

        $page_size = (int) $this->request->input('page_size', 10);
        $page_size = $page_size > 0 ? min($page_size, 50) : 1;
        $result = $query->paginate($page_size);
        return $this->success('请求成功', [
            'page' => $result->currentPage(),
            'total' => $result->total(),
            'items' => $result->items()
        ]);
    }
}